package com.itheima.web3.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionUtil {
    private static final SqlSessionFactory sqlSessionFactory;
    static {
        //核心配置文件的路径
        String resource = "mybatis-config.xml";
        try {
            //获取一个字节输入流
            InputStream is = Resources.getResourceAsStream(resource);
            //构建一个sqlSessionFactory对象
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private SqlSessionUtil() {
    }
    public static SqlSession createSqlSession(boolean autoCommit) {
        return sqlSessionFactory.openSession(autoCommit); //是否自动提交事务
    }
    //默认手动提交事务
    public static SqlSession createSqlSession() {
        return sqlSessionFactory.openSession();
    }
    //关闭sqlSession
    public static void closeSqlSession(SqlSession sqlSessions) {
        if (sqlSessions != null) {
            sqlSessions.close();
        }
    }
    public static void commit(SqlSession sqlSessions) {
        if (sqlSessions != null) {
            sqlSessions.commit();
            SqlSessionUtil.closeSqlSession(sqlSessions);
        }

    }
    public static void rollback(SqlSession sqlSessions) {
        if (sqlSessions != null) {
            sqlSessions.rollback();
            SqlSessionUtil.closeSqlSession(sqlSessions);
        }
    }
}
